package com.app.studyroom;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.message.LearningRankingItem;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LearningRankingActivity extends BaseActivity {

    private ImageView ic_back;
    private TextView[] userNames = new TextView[8];
    private TextView[] userTimes = new TextView[8];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learning_ranking);

        ic_back = findViewById(R.id.ic_back);
        ic_back.setOnClickListener(v -> onBackPressed());

        // 绑定前 8 名的姓名和时长视图
        for (int i = 0; i < 8; i++) {
            int nameResId = getResources().getIdentifier("userName" + (i + 1), "id", getPackageName());
            int timeResId = getResources().getIdentifier("userTime" + (i + 1), "id", getPackageName());
            userNames[i] = findViewById(nameResId);
            userTimes[i] = findViewById(timeResId);
        }

        loadRankingData();
    }

    private void loadRankingData() {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getLearningRanking().enqueue(new Callback<ApiResponse<List<LearningRankingItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<LearningRankingItem>>> call, Response<ApiResponse<List<LearningRankingItem>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<LearningRankingItem> data = response.body().getData();

                    // 确保数据长度为 8，不足补“虚位以待”
                    for (int i = 0; i < 8; i++) {
                        if (i < data.size()) {
                            userNames[i].setText(data.get(i).getUserName());
                            userTimes[i].setText(data.get(i).getStudyTime());
                        } else {
                            userNames[i].setText("虚位以待");
                            userTimes[i].setText("--");
                        }
                    }
                } else {
                    String msg = (response.body() != null) ? response.body().getMessage() : "请求失败";
                    Toast.makeText(LearningRankingActivity.this, "加载失败：" + msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<LearningRankingItem>>> call, Throwable t) {
                Toast.makeText(LearningRankingActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

